package com.ikun.hospayservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.ikun.common.entity.Convention;
import com.ikun.hospayservice.config.AliPayConfig;
import com.ikun.hospayservice.pojo.AliPay;
import com.ikun.hospayservice.service.AliPayService;
import com.ikun.hospayservice.utils.ProcessOrdersUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


/**
 * @author sun12
 */
@Slf4j
@Service
public class AliPayServiceImpl implements AliPayService {

    @Autowired
    private AliPayConfig aliPayConfig;

    @Resource
    private ProcessOrdersUtil processOrdersUtil;

    /**
     * 付款
     */
    @Override
    public String payment(Convention convention) {
        try {
            // 创建客户端
            DefaultAlipayClient aliPayClient = this.creatAliPayClient();
            // 创建API对应的request
            AlipayTradePagePayRequest aliPayRequest = new AlipayTradePagePayRequest();
            aliPayRequest.setReturnUrl(aliPayConfig.getReturnUrl());
            aliPayRequest.setNotifyUrl(aliPayConfig.getNotifyUrl());
            //创建支付宝订单对象  創建之前的預約對象應該是没有订单号的，创建后有了,且与支付宝订单对象属于同一个
            AliPay aliPay = processOrdersUtil.createAliPayOrder(convention);
            // 设置请求参数
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", aliPay.getTraceNo());
            bizContent.put("total_amount", aliPay.getTotalAmount());
            bizContent.put("subject", aliPay.getSubject());
            bizContent.put("product_code", aliPay.getProductCode());
            bizContent.put("time_expire", aliPay.getOvertime());
            aliPayRequest.setBizContent(bizContent.toString());
            //生成支付宝订单，返回支付页面
            AlipayTradePagePayResponse response = aliPayClient.pageExecute(aliPayRequest, "POST");
            //在預約表生成預約訂單，填入支付宝对象的订单号,无论是否支付都需要创建预约订单
            convention.setTradeNo(aliPay.getTraceNo());
            processOrdersUtil.createOrder(convention);
            //减少余号数
            processOrdersUtil.reduceSurplus(convention);
            //判断支付是否成功
            if (response.isSuccess()) {
                //输出
                log.info("支付调用成功={}", response.getBody());
                log.info("支付调用成功={}", aliPay);
            } else {
                //更新预约信息状态
                processOrdersUtil.updateOrder(convention);
                //增加余号数
                processOrdersUtil.addSurplus(convention);
                log.info("支付调用失敗={}", response.getBody());
            }
//            String result = aliPayClient.pageExecute(aliPayRequest, "POST").getBody();
//            log.info("返回结果={}", result);
            return response.getBody();
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 取消支付
     *
     * @param convention
     */
    @Override
    public void cancelPay(Convention convention) {
        try {
            DefaultAlipayClient aliPayClient = this.creatAliPayClient();
            AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
            //创建支付宝订单对象
            AliPay aliPay = processOrdersUtil.createAliPayOrder(convention);
            //设置请求参数
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", aliPay.getTraceNo());
            request.setBizContent(bizContent.toString());
            AlipayTradeCloseResponse response = aliPayClient.execute(request);
            if (response.isSuccess()) {
                log.info("取消支付调用成功={}", response);
            } else {
                log.info("取消支付调用失败={}", response);
            }
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 退款
     */
    @Override
    public int refund(Convention convention) {
        try {
            //获得初始化的AlipayClient
            DefaultAlipayClient aliPayClient = this.creatAliPayClient();
            //设置请求参数
            AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
            //创建支付宝订单对象
            AliPay aliPay = processOrdersUtil.createAliPayOrder(convention);
            //设置请求参数
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", aliPay.getTraceNo());
            bizContent.put("refund_amount", aliPay.getTotalAmount());
            bizContent.put("out_request_no", "HZ01RF001");
            alipayRequest.setBizContent(bizContent.toString());
            //请求
            AlipayTradeRefundResponse response = aliPayClient.execute(alipayRequest);
            //判断退款成功状态
            if (response.isSuccess()) {
                //更新预约信息状态
                processOrdersUtil.updateOrder(convention);
                //增加余号数
                processOrdersUtil.addSurplus(convention);
                log.info("退款调用成功={}", response);
                log.info("退款调用成功={}", aliPay);
                return 200;
            } else {
                log.info("退款调用失败={}", response);
                log.info("退款调用失败={}", aliPay);
                return 500;
            }
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 查询支付状态
     */
    @Override
    public String queryState(String alipayTraceNo) {
        try {
            DefaultAlipayClient aliPayClient = this.creatAliPayClient();
            AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
            alipayRequest.setBizContent(
                    "{\"out_trade_no\":\"" + alipayTraceNo + "\"," +
                            "\"query_options\":[\"trade_settle_info\"]}");
            AlipayTradeQueryResponse response = aliPayClient.execute(alipayRequest);
            if (response.isSuccess()) {
                log.info("查询支付状态调用成功={}", response);
            } else {
                log.info("查询支付状态调用失败={}", response);
            }
            return response.getBody();
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }


    public DefaultAlipayClient creatAliPayClient() {
        return new DefaultAlipayClient(
                aliPayConfig.getGateway(), aliPayConfig.getAppId(), aliPayConfig.getAppPrivateKey(),
                aliPayConfig.getFormat(), aliPayConfig.getCharset(), aliPayConfig.getPublicKey(),
                aliPayConfig.getSignType());
    }

}
